package leetcode.剑指offer.后40;

import org.junit.Test;

import java.util.*;

/**
 * @author ：zsy
 * @date ：Created 2021/7/26 17:09
 * @description：https://leetcode-cn.com/problems/fan-zhuan-dan-ci-shun-xu-lcof/
 */
public class 剑指_58_I_翻转单词顺序 {
    @Test
    public void test() {
        Solution solution = new Solution();
        System.out.println(solution.reverseWords("  hello world!  "));
    }

    class Solution {
        public String reverseWords(String s) {
            s = s.trim();
            int j = s.length() - 1;
            int i = j;
            StringBuilder builder = new StringBuilder();
            while (i >= 0) {
                while (i >= 0 && s.charAt(i) != ' ') i--;
                builder.append(s.substring(i + 1, j + 1) + " ");
                while (i >= 0 && s.charAt(i) == ' ') i--;
                j = i;
            }
            return builder.toString().trim();
        }
    }

}
